package clock.socoolby.com.clock.pop;


import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.haibin.calendarview.Calendar;
import com.haibin.calendarview.CalendarLayout;
import com.haibin.calendarview.CalendarView;
import com.idanatz.oneadapter.OneAdapter;
import com.idanatz.oneadapter.external.modules.EmptinessModule;
import com.idanatz.oneadapter.external.modules.EmptinessModuleConfig;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import clock.socoolby.com.clock.R;
import clock.socoolby.com.clock.alter.AlterManager;
import clock.socoolby.com.clock.event.ClockEvent;
import clock.socoolby.com.clock.event.ClockEventListener;
import clock.socoolby.com.clock.event.EventManger;
import clock.socoolby.com.clock.net.auth.AuthCallback;
import clock.socoolby.com.clock.todo.TodoSyncServiceManager;
import clock.socoolby.com.clock.todo.microsoft.MicrosoftTodoSyncServiceImpl;
import clock.socoolby.com.clock.todo.microsoft.adapter.TodoEntityAdapter;
import clock.socoolby.com.clock.todo.microsoft.bean.todo.TodoEntity;

public class CalendarPopup extends FullScreenDialogFragment implements CalendarView.OnCalendarSelectListener, CalendarView.OnYearChangeListener{

    public static final String TAG=CalendarPopup.class.getCanonicalName();

    TodoSyncServiceManager todoSyncServiceManager;


    public CalendarPopup(AlterManager alterManager,TodoSyncServiceManager todoSyncServiceManager) {
        this.alterManager=alterManager;
        this.todoSyncServiceManager=todoSyncServiceManager;
    }

    TextView mTextMonthDay;

    TextView mTextYear;

    TextView mTextLunar;

    TextView mTextCurrentDay;

    CalendarView mCalendarView;

    RelativeLayout mRelativeTool;
    private int mYear;
    CalendarLayout mCalendarLayout;

    AlterManager alterManager;

    RecyclerView recyclerView;

    OneAdapter todoAdapter;

    ImageView todo_sync;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View content=inflater.inflate(R.layout.pop_calendar,container);
        mTextMonthDay = (TextView) content.findViewById(R.id.tv_month_day);
        mTextYear = (TextView) content.findViewById(R.id.tv_year);
        mTextLunar = (TextView) content.findViewById(R.id.tv_lunar);
        mRelativeTool = (RelativeLayout) content.findViewById(R.id.rl_tool);
        mCalendarView = (CalendarView) content.findViewById(R.id.calendarView);
        mTextCurrentDay = (TextView) content.findViewById(R.id.tv_current_day);
        recyclerView=content.findViewById(R.id.recyclerView);
        todo_sync=content.findViewById(R.id.ib_todo_sync);
        todo_sync.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                syncNetTodo();
            }
        });

        if(!todoSyncServiceManager.isServiceAble())
            todo_sync.setVisibility(View.GONE);

        mTextMonthDay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!mCalendarLayout.isExpand()) {
                    mCalendarLayout.expand();
                    return;
                }
                mCalendarView.showYearSelectLayout(mYear);
                mTextLunar.setVisibility(View.GONE);
                mTextYear.setVisibility(View.GONE);
                mTextMonthDay.setText(String.valueOf(mYear));
            }
        });
        content.findViewById(R.id.fl_current).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mCalendarView.scrollToCurrent();
                mCalendarLayout.shrink();
            }
        });
        content.findViewById(R.id.tv_handup_time_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
            }
        });
        mCalendarLayout =content.findViewById(R.id.calendarLayout);
        mCalendarView.setOnCalendarSelectListener(this);
        mCalendarView.setOnYearChangeListener(this);
        mTextYear.setText(String.valueOf(mCalendarView.getCurYear()));
        mYear = mCalendarView.getCurYear();
        mTextMonthDay.setText(mCalendarView.getCurMonth() + "月" + mCalendarView.getCurDay() + "日");
        mTextLunar.setText("今日");
        mTextCurrentDay.setText(String.valueOf(mCalendarView.getCurDay()));

        recyclerView.setLayoutManager(new LinearLayoutManager(inflater.getContext()));

        todoAdapter = new OneAdapter()
                .attachItemModule(new TodoEntityAdapter())
                .attachEmptinessModule(new EmptinessModule() {
                    @Override
                    public EmptinessModuleConfig provideModuleConfig() {
                        return new EmptinessModuleConfig() {
                            @Override
                            public int withLayoutResource() {
                                return R.layout.entity_null;
                            }
                        };
                    }
                })
                .attachTo(recyclerView);

        initData();

        mCalendarView.setOnViewChangeListener(isMonthView->{
             if(isMonthView){
                 mRelativeTool.setVisibility(View.VISIBLE);
             }else
                 mRelativeTool.setVisibility(View.GONE);
        });

        mCalendarView.setOnWeekChangeListener(new CalendarView.OnWeekChangeListener() {
            @Override
            public void onWeekChange(List<Calendar> weekCalendars) {

            }
        });

        EventManger.addToduSyncSeccuss(this, new ClockEventListener<String>() {
            @Override
            public void onEvent(ClockEvent<String> event) {
                initSyncTodoData();
                todo_sync.setClickable(true);
                Toast.makeText(getContext(), "同步完成。。。", Toast.LENGTH_SHORT).show();
            }
        });

        mCalendarView.scrollToCurrent();

        return content;
    }

    public void setCurrentDay(){
        mCalendarView.scrollToCurrent();
    }


    @Override
    public void onCalendarOutOfRange(Calendar calendar) {

    }

    private void syncNetTodo(){
        todo_sync.setClickable(false);
        todoSyncServiceManager.singIn(MicrosoftTodoSyncServiceImpl.NAME, getActivity(), new AuthCallback() {
            @Override
            public void onSuccess() {
                todoSyncServiceManager.startSyncAllEntitys();
            }

            @Override
            public void onError(Exception exception) {
                todo_sync.setClickable(true);
            }

            @Override
            public void onCancel() {
                todo_sync.setClickable(true);
            }
        });
    }

    @Override
    public void onCalendarSelect(Calendar calendar, boolean isClick) {
        mTextLunar.setVisibility(View.VISIBLE);
        mTextYear.setVisibility(View.VISIBLE);
        mTextMonthDay.setText(calendar.getMonth() + "月" + calendar.getDay() + "日");
        mTextYear.setText(String.valueOf(calendar.getYear()));
        mTextLunar.setText(calendar.getLunar());
        mYear = calendar.getYear();

        todoAdapter.clear();
        List<TodoEntity> dayEntityList=todoSyncServiceManager.getTodoEntities(calendar.getYear(),calendar.getMonth()-1,calendar.getDay());
        timber.log.Timber.d("onCalendarSelect on month:"+calendar.getMonth()+"\t list size:"+dayEntityList.size());
        if(dayEntityList.size()>0)
           todoAdapter.setItems(dayEntityList);
    }

    @Override
    public void onYearChange(int year) {
        mTextMonthDay.setText(String.valueOf(year));
    }

    protected void initData() {
        //initTestData();
        if(todoSyncServiceManager.isServiceAble())
            initSyncTodoData();
    }

    protected void initSyncTodoData(){
        Map<String, Calendar> map = new HashMap<>();
        Calendar todoCalendar;
        timber.log.Timber.d("total todos :"+todoSyncServiceManager.getTodoEntities().size());
        for(TodoEntity todoEntity:todoSyncServiceManager.getTodoEntities()){
            //timber.log.Timber.d("todo name:"+todoEntity.getSubject()+"create time:"+todoEntity.getCreateddatetime());
            if(todoEntity.getCreateddatetime()!=null){
                todoCalendar=getSchemeCalendar(todoEntity.getCreateddatetime(),0xFF40db25,todoEntity.getSubject());
                map.put(todoCalendar.toString(),todoCalendar);
                //timber.log.Timber.d("todo to show:"+todoCalendar.toString());
            }
        }
        mCalendarView.setSchemeDate(map);
    }

    protected void initTestData() {
        int year = mCalendarView.getCurYear();
        int month = mCalendarView.getCurMonth();

        Map<String, Calendar> map = new HashMap<>();
        map.put(getSchemeCalendar(year, month, 3, 0xFF40db25, "假").toString(),
                getSchemeCalendar(year, month, 3, 0xFF40db25, "假"));
        map.put(getSchemeCalendar(year, month, 6, 0xFFe69138, "事").toString(),
                getSchemeCalendar(year, month, 6, 0xFFe69138, "事"));
        map.put(getSchemeCalendar(year, month, 9, 0xFFdf1356, "议").toString(),
                getSchemeCalendar(year, month, 9, 0xFFdf1356, "议"));
        map.put(getSchemeCalendar(year, month, 13, 0xFFedc56d, "记").toString(),
                getSchemeCalendar(year, month, 13, 0xFFedc56d, "记"));
        map.put(getSchemeCalendar(year, month, 14, 0xFFedc56d, "记").toString(),
                getSchemeCalendar(year, month, 14, 0xFFedc56d, "记"));
        map.put(getSchemeCalendar(year, month, 15, 0xFFaacc44, "假").toString(),
                getSchemeCalendar(year, month, 15, 0xFFaacc44, "假"));
        map.put(getSchemeCalendar(year, month, 18, 0xFFbc13f0, "记").toString(),
                getSchemeCalendar(year, month, 18, 0xFFbc13f0, "记"));
        map.put(getSchemeCalendar(year, month, 22, 0xFFdf1356, "议").toString(),
                getSchemeCalendar(year, month, 22, 0xFFdf1356, "议"));
        map.put(getSchemeCalendar(year, month, 25, 0xFF13acf0, "假").toString(),
                getSchemeCalendar(year, month, 25, 0xFF13acf0, "假"));
        map.put(getSchemeCalendar(year, month, 27, 0xFF13acf0, "多").toString(),
                getSchemeCalendar(year, month, 27, 0xFF13acf0, "多"));
        //此方法在巨大的数据量上不影响遍历性能，推荐使用
        mCalendarView.setSchemeDate(map);
    }

    private Calendar getSchemeCalendar(int year, int month, int day, int color, String text) {
        Calendar calendar = new Calendar();
        calendar.setYear(year);
        calendar.setMonth(month);
        calendar.setDay(day);
        calendar.setSchemeColor(color);//如果单独标记颜色、则会使用这个颜色
        calendar.setScheme(text);
        calendar.addScheme(color, "假");
        calendar.addScheme(day%2 == 0 ? 0xFF00CD00 : 0xFFD15FEE, "节");
        calendar.addScheme(day%2 == 0 ? 0xFF660000 : 0xFF4169E1, "记");
        return calendar;
    }

    private Calendar getSchemeCalendar(Date date,int color,String text){
        java.util.Calendar temp=java.util.Calendar.getInstance();
        temp.setTime(date);
        Calendar calendar = new Calendar();
        calendar.setYear(temp.get(java.util.Calendar.YEAR));
        calendar.setMonth(temp.get(java.util.Calendar.MONTH)+1);
        calendar.setDay(temp.get(java.util.Calendar.DAY_OF_MONTH));
        calendar.setSchemeColor(color);//如果单独标记颜色、则会使用这个颜色
        calendar.setScheme(text);
        calendar.addScheme(color, "假");
        //calendar.addScheme(day%2 == 0 ? 0xFF00CD00 : 0xFFD15FEE, "节");
        //calendar.addScheme(day%2 == 0 ? 0xFF660000 : 0xFF4169E1, "记");
        return calendar;
    }
}
